package cn.nohan.funplay.module.member.mongo.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.List;

/**
 * @author caozhipeng
 * @date 2025/7/21
 */

//@Configuration
public class JacksonConfig {

//    @Bean
    public Module nullListModule() {
        return new SimpleModule() {
            @Override
            public void setupModule(SetupContext context) {
                context.addBeanSerializerModifier(new BeanSerializerModifier() {
                    @Override
                    public List<BeanPropertyWriter> changeProperties(
                            SerializationConfig config,
                            BeanDescription beanDesc,
                            List<BeanPropertyWriter> beanProperties
                    ) {
                        // 为每个List类型的属性配置null序列化器
                        for (BeanPropertyWriter writer : beanProperties) {
                            if (isListType(writer)) {
                                writer.assignNullSerializer(NullListSerializer.INSTANCE);
                            }
                            if (isStringType(writer)) {
                                writer.assignNullSerializer(NullStringSerializer.INSTANCE);
                            }
                        }
                        return beanProperties;
                    }
                });
            }
        };
    }

    // 判断属性是否为List类型
    private boolean isListType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return clazz != null && List.class.isAssignableFrom(clazz);
    }

    private boolean isStringType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return clazz != null && String.class.isAssignableFrom(clazz);
    }

    // 处理null List的自定义序列化器
    public static class NullListSerializer extends JsonSerializer<Object> {
        public static final NullListSerializer INSTANCE = new NullListSerializer();

        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeStartArray(); // 输出空数组：[]
            gen.writeEndArray();
        }

    }

    public static class NullStringSerializer extends JsonSerializer<Object> {
        public static final NullStringSerializer INSTANCE = new NullStringSerializer();

        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeString("");
        }

    }
}
